package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import com.elite.groovy.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: autoGwPushClue*
 * @Description:官微-自动推送线索
 * @remak ：官微-自动推送线索
 * @author: TH*
 * @date 2023-12-05 11:11:00
 *
 */
public class autoGwPushClue implements ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(autoGwPushClue.class);

    @Override
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        String requstbody=null;
        try {
            //查找待推送
            String SelectSql = '''
                           Select 
                           rec_guid,
                           task_guid,
                           to_char(sysdate, 'YYYY-mm-dd hh24:mm:ss') as zz,
                           STAFF_ID
                           from 
                           GW_UPDATECLUE_LIST
                           where FLAG='0'
                           and rownum<=500
                          ''';


            List<Map<String, Object>> SelectList = jt.queryForList(SelectSql);


            for (int i = 0; i < SelectList.size(); i++) {
                Map YpfMap = SelectList.get(i);
                String task_guid = YpfMap.get("TASK_GUID");//任务ID
                String rec_guid = YpfMap.get("REC_GUID");//主键
                String assignedDate = YpfMap.get("ZZ");//时间
                String STAFF_ID = YpfMap.get("STAFF_ID");//人员ID
                String waterNo = KHUtil.getRandomString(36);


                String  STAFFSQL='''select loginname,staffname from staff where staff_id=?''';

                List<Map<String, Object>> staffList = jt.queryForList(STAFFSQL,STAFF_ID);

                String loginname=staffList.get(0).get("loginname");
                String staffname=staffList.get(0).get("staffname");

                requstbody = """
{
    "clueId": "${task_guid}",
    "waterNo": "${waterNo}",
    "assignedType": "1",
    "operateName": "系统",
    "operateCode": "SELITE",
    "assignedName": "${staffname}",
    "assignedCode": "${loginname}",
    "assignedDate": "${assignedDate}"
} 
""";



                log.debug("【官微-线索更新clueassigned】接口请求报文：" + requstbody.toString());

                String sql2 = "select WEBSERVICEURL From sysc_interface where WEBTYPE='GW_URL'";
                List<Map<String, Object>> groovyUrl = jt.queryForList(sql2)
                String geturl = groovyUrl.get(0).get("WEBSERVICEURL");


                String requestpath = geturl.toString() + "/blue-scrm/breakpoint/clueassigned";

                log.debug("【官微-线索更新clueassigned】请求地址URL：" + requestpath.toString());
                //设置请求表头
                Map<String, String> TokenParams = new HashMap<String, String>();
                TokenParams.put("Content-Type", "application/json");
                String gwponsebody = Util.doHttpPostUseHead(requestpath.toString(), requstbody.toString(), "UTF-8", 20000, 0, TokenParams, "");


              if (!KHUtil.isNull(gwponsebody)){
                  JSONObject  bodyjson= JSONObject.fromObject(gwponsebody);
                  log.debug("【官微-线索更新clueassigned】返回参数：" + bodyjson.toString());
                  String code=GetJV(bodyjson,"code");

                  if (code.equals("200")){
                      log.debug("线索更新成功!")
                      String updateSql='''Update  GW_UPDATECLUE_LIST set flag='1',UPDATEDDATE=sysdate where rec_guid=?   ''';
                      jt.update(updateSql,rec_guid);
                      String insertsql='''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'autoGwPushClue',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

                      jt.update(insertsql,requstbody.toString(),bodyjson.toString());

                  }else{
                      log.debug("线索更新失败!")
                      String updateSql='''Update  GW_UPDATECLUE_LIST set flag='-1',UPDATEDDATE=sysdate where rec_guid=?   ''';
                      jt.update(updateSql,rec_guid);
                      String insertsql='''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'autoGwPushClue',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

                      jt.update(insertsql,requstbody.toString(),bodyjson.toString());

                  }


              }


            }


        } catch (Exception e) {
            log.error("【官微】自动推送线索异常：" + e.getMessage());
            String insertsql='''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'autoGwPushClue',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';
            jt.update(insertsql,requstbody.toString(),bodyjson.toString());
        }


    }

    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }
}
